import React from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { stringify } from 'qs';
import { message } from 'antd';
import List from './components/List';
import Modal from './components/Modal';

@connect(({ loading, admin, role }) => ({ loading, admin, role }))
class Admin extends React.Component {
  static defaultProps = {
    
  };

  handleRefresh = newQuery => {
    const { location } = this.props;
    const { query, pathname } = location;

    router.push({
      pathname,
      search: stringify(
        {
          ...query,
          ...newQuery,
        },
        { arrayFormat: 'repeat' },
      ),
    });
  };

  get listProps() {
    const { admin, loading, dispatch } = this.props;
    const { pagination, list } = admin;

    return {
      dataSource: list,
      loading: loading.effects['admin/query'],
      pagination,
      bordered: false,
      onAdd() {
        dispatch({
          type: 'admin/showModal',
          payload: {
            modalType: 'create',
          },
        });
      },
      onEditItem: item => {
        dispatch({
          type: 'admin/showModal',
          payload: {
            modalType: 'update',
            currentItem: item,
          },
        });
      },
      onDeleteItem: id => {
        dispatch({
          type: 'admin/delete',
          payload: id,
        }).then(res => {
          if(res.code === 500){
            message.error(res.msg);
          }else{
            this.handleRefresh({
              page:
                list.length === 1 && pagination.current > 1
                  ? pagination.current - 1
                  : pagination.current,
            });
          }
        });
      },
    };
  }

  get modalProps() {
    const { dispatch, admin, loading } = this.props;
    const { currentItem, modalVisible, modalType, roleList } = admin;

    return {
      item: modalType === 'create' ? {} : currentItem,
      visible: modalVisible,
      destroyOnClose: true,
      maskClosable: false,
      confirmLoading: loading.effects[`admin/${modalType}`],
      title: `${modalType === 'create' ? '新建' : '编辑'}管理员`,
      centered: true,
      roleList,
      onOk: data => {
        dispatch({
          type: `admin/${modalType}`,
          payload: data,
        }).then(() => {
          this.handleRefresh();
        });
      },
      onCancel() {
        dispatch({
          type: 'admin/hideModal',
        });
      },
    };
  }

  render() {
    return (
      <PageHeaderWrapper title={'管理员列表'} breadcrumb={false}>
        <List {...this.listProps} />
        <Modal {...this.modalProps} />
      </PageHeaderWrapper>
    );
  }
}

export default Admin;
